﻿namespace dot_in.HTWKAidStation.Client.Menu
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    public static class MenuParser
    {
        public static List<Menu> GetAllMenuItems(string html)
        {
            return SplitMenuItems(html).Select(ParseMenuItem).ToList();
        }

        private static IEnumerable<string> SplitMenuItems(string html)
        {
            List<string> result = new List<string>();
            Match match = Regex.Match(html, "<div class=.menu.>");
            match = match.NextMatch();
            while (match.Success)
            {
                result.Add(html.Substring(0, match.Index));
                html = html.Substring(match.Index);
                match = Regex.Match(html, "<div class=.menu.>");
                match = match.NextMatch();
            }

            result.Add(html);

            return result;
        }

        private static Menu ParseMenuItem(string html)
        {
            Menu result = new Menu
                                  {
                                      ItemTitle =
                                          Regex.Match(html, ".menu_title.><span>([^<]*?)</span>").Groups[1].Value,
                                      SubTitle = Regex.Match(html, ".menu_name1.>([^<]*?)</div>").Groups[1].Value,
                                      Content = ParseItemContent(html),
                                      PriceString = ParseItemPrice(html)
                                  };

            return result;
        }

        private static string ParseItemContent(string html)
        {
            string result = Regex.Matches(html, ".menu_name2.>([^<]*?)</div>").Cast<Match>().Aggregate(
                string.Empty, (current, match) => current + (match.Groups[1].Value + ", "));
            result = result.TrimEnd(new[] { ',', ' ' });
            return result;
        }

        private static string ParseItemPrice(string html)
        {
            string result = Regex.Replace(Regex.Match(html, ".menu_price.>([^<]*?)</div>").Groups[1].Value, "&euro;", "€");
            return result;
        }
    }
}
